package com.andy.common.util;

import au.com.bytecode.opencsv.CSVReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiangjh on 2017/8/31.
 */
public class ExcelUtil implements Closeable {
    private static final Logger LOG = LoggerFactory.getLogger(ExcelUtil.class);
    private static FileInputStream inputStream;
    private static InputStreamReader isr;
    private static CSVReader reader;

    public static List<String[]> loadFile(String filePath) {
        List<String[]> lines = null;
        try {
            inputStream = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            LOG.error("File Not Found , File Path is {} ,error is {}", filePath , e);
        }
        isr = new InputStreamReader(inputStream);
        reader = new CSVReader(isr);
        try {
            lines = reader.readAll();
        } catch (IOException e) {
            LOG.error("read line fail reason is {}", e);
        }
        return lines;
    }

    public static List<String> NioLoadFile(String filePath) {
        List<String> line = new ArrayList<String>();
        try {
            ByteBuffer bf = ByteBuffer.allocate(1024 * 1024 * 10); //10MB
            inputStream = new FileInputStream(filePath);
            FileChannel channel = inputStream.getChannel();
            while (true) {
                bf.clear();
                int r = channel.read(bf);
                if (r == -1) {
                    break;
                }
                line.add(new String(bf.array()));
            }
        } catch (FileNotFoundException e) {
            LOG.error("File Not Found , File Path is {} ,error is {}", filePath, e);
        } catch (IOException e) {
            LOG.error("channel read buff error {}", e);
        }
        return line;
    }

    public void close() throws IOException {
        if (reader != null)
            reader.close();
        if (isr != null)
            isr.close();
        if (inputStream != null)
            inputStream.close();
    }

 
}
